package com.example.im.ui.adapter

import android.content.Context
import android.text.Html
import android.text.Spanned
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.entity.FriendOrRoom
import com.xlkj.ehobe.storage.ui.adapter.holder.RecyclerViewHolder
import kotlinx.android.synthetic.main.recycler_item_search.view.*


class SearchFriendAdapter(
    private val mContext: Context,
    private val friendOrRooms: MutableList<FriendOrRoom>
) :
    RecyclerView.Adapter<RecyclerViewHolder>() {

    private var keyword: String = ""

    fun setKeyword(keyword: String) {
        this.keyword = keyword
    }

    private var mOnClickItemListener: OnClickItemListener? = null

    fun setOnItemClickListener(mOnClickItemListener: OnClickItemListener) {
        this.mOnClickItemListener = mOnClickItemListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(mContext).inflate(
                R.layout.recycler_item_search, parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {

        val view: View = holder.itemView
        view.tv_name.text = spanned(friendOrRooms[position].nickname!!, keyword)
        view.tv_user_name.text = spanned(friendOrRooms[position].account!!, keyword)
        view.setOnClickListener { v ->
            mOnClickItemListener!!.onClickItemFriend(v, position)
        }
        view.tag = position
    }

    override fun getItemCount(): Int {
        return friendOrRooms.size
    }

    /**
     * 添加所有数据
     * */
    fun addData(friends: MutableList<FriendOrRoom>) {
        this.friendOrRooms.clear()
        this.friendOrRooms.addAll(friends)
        this.notifyDataSetChanged()
    }

    interface OnClickItemListener {
        fun onClickItemFriend(view: View, position: Int)
    }

    /**
     * 根据关键字，指定单个部分文字颜色
     */
    private fun spanned(text: String, keyword: String): Spanned {
        return Html.fromHtml(text.replace(keyword, "<font color=#00C6FD>$keyword</font>"))
    }
}
